package com.ias.agdis_r.activity.task;

import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import androidx.fragment.app.Fragment;
//import android.support.v4.app.FragmentManager;
import androidx.fragment.app.FragmentManager;
//import android.support.v4.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentPagerAdapter;
//import android.support.v4.app.FragmentTransaction;
import androidx.fragment.app.FragmentTransaction;
//import android.support.v4.view.ViewPager;
import androidx.viewpager.widget.ViewPager;
//import android.support.v4.view.ViewPager.OnPageChangeListener;
import androidx.viewpager.widget.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseFragmentActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.task.Task;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.fragment.box.BoxTabTask;
import com.ias.agdis_r.fragment.task.TaskInfoTab01;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.response.SubmittaskprocssResponse;
import com.ias.agdis_r.terminalmanager.restful.task.endpoint.response.SubmittaskvnbResponse;
import com.ias.agdis_r.terminalmanager.restful.task.vo.SubmitTaskProcessResponseVO;
import com.ias.agdis_r.terminalmanager.restful.task.vo.SubmitTaskVnbResponseVO;

import java.util.ArrayList;
import java.util.List;

/**
 * 任务详情界面
 *
 * @author guoxr
 */
public class TaskInfoActivity extends BaseFragmentActivity implements OnClickListener,OnGestureListener {
    private ViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private ActionBar actionBar = null;
    private TaskInfoTab01 tab01;
    //private TaskInfoTab02 tab02;
    protected Task task = null;
    protected String tnb = "";
    private boolean ishis = false;
    private GestureDetector detector;

//    private TextView tabText1, tabText2;
//    /**
//     * 顶部两个LinearLayout
//     */
//    private LinearLayout mTabtask;
//    private LinearLayout mTabtaskdone;
    /**
     * ViewPager的当前选中页
     */
    private int currentIndex;
    /**
     * 屏幕的宽度
     */
    private int screenWidth;

    public TaskInfoActivity() {
        super();
        //保存TaskInfoActivity
        DataBaseManager.getInstance().setTaskInfoActivity(this);
    }

    @Override
    public void finish() {
        super.finish();
        // 清空保存的TaskInfoActivity
        DataBaseManager.getInstance().setTaskInfoActivity(null);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_TASKEXE.toString())) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.no_AI_T_TASKEXE), false);
            finish();
        }
        detector = new GestureDetector(this,this);//滑屏简体器 Zhangsc Add
        setContentView(R.layout.activity_taskinfo);
        actionBar = getActionBar();
        taskinfoactionbar();
        Intent intent = getIntent();
        tnb = intent.getExtras().getString(MessageModel.TNB);
        ishis = intent.getExtras().getBoolean("ishis");
        isAllCheck(new String[]{tnb, JavaBeanManager.getInstance().getUserinfo().getEnb()});
        initViews();
        loadData();
        initFragments();
        //initDatas();
        //initEvents();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!ishis){
            if (task.getPID().equals(MessageModel.TCXX)
                    || task.getPID().equals(MessageModel.TEND)
                    || task.getPID().equals(MessageModel.TRJT)) {
                finish();
            }else{
                Refresh();
            }
        }
    }

    /**
     * 标记此tnb下的所有变更消息为已读
     */
    private void isAllCheck(String[] selectionArgs) {
        // TODO Auto-generated method stub
        BoxDBHelper dbHelper = new BoxDBHelper(DataBaseManager.getInstance()
                .getContext());
        int i = dbHelper.isAllCheck("select count(1) from "
                + BoxDBHelper.TABLE_TASK
                + " where ischeck=0 and tnb=? and enb = ?", selectionArgs);
        if (i > 0) {
            dbHelper.setCheck(BoxDBHelper.TABLE_TASK, "tnb = ? and enb = ?",
                    selectionArgs);
            DataManager.getInstance().setUnCheckNumber(
                    DataManager.getInstance().getUnCheckNumber() - i);
            setResult(BoxTabTask.RESULTCODE);
        }
        dbHelper.closeDB();
    }

    private void initViews() {
//        tabText1 = (TextView) findViewById(R.id.id_task);
//        tabText1.setText(R.string.taskexe);
//        tabText2 = (TextView) findViewById(R.id.id_taskhis);
//        tabText2.setText(R.string.taskprocess);
//        mTabtask = (LinearLayout) findViewById(R.id.id_tab_task);
//        mTabtaskdone = (LinearLayout) findViewById(R.id.id_tab_taskhis);
//        mTabtask.setOnClickListener(this);
//        mTabtaskdone.setOnClickListener(this);
//        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
    }

    protected void loadData() {
        Task temp = DataManager.getInstance().getWorkTask(tnb);
        if (null == temp) {
            temp = DataManager.getInstance().getHistoryWorkTask(tnb);
        }
        if (null == temp) {
            temp = DataManager.getInstance().getReceiveTask(tnb);
        }
        task = temp;
        if (null != task) {
            JavaBeanManager.getInstance().getUserinfo().setMytnb(tnb);
        } else {
            Log.i("loadData()", "任务为空");
        }
    }

    private void taskinfoactionbar() {
        // TODO Auto-generated method stub
        actionBar.setCustomView(LayoutInflater.from(TaskInfoActivity.this)
                .inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        TextView title = (TextView) findViewById(R.id.txt_title);
        title.setText(R.string.TaskInfoActivity);
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TaskInfoActivity.this,
                        MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }

    private void initEvents() {
        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                resetTextView();
                switch (position) {
                    case 0:
//                        tabText1.setTextColor(getResources().getColor(R.color.green));
                        break;
                    case 1:
//                        tabText2.setTextColor(getResources().getColor(R.color.green));
                        break;
                }
                currentIndex = position;
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
//
//                /**
//                 * 利用position和currentIndex判断用户的操作是哪一页往哪一页滑动
//                 * 然后改变根据positionOffset动态改变TabLine的leftMargin
//                 */
//                if (currentIndex == 0 && position == 0)// 0->1
//                {
//                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
//                            .getLayoutParams();
//                    lp.leftMargin = (int) (positionOffset
//                            * (screenWidth * 1.0 / 2) + currentIndex
//                            * (screenWidth / 2));
//                    mTabLine.setLayoutParams(lp);
//
//                } else if (currentIndex == 1 && position == 0) // 1->0
//                {
//                    LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) mTabLine
//                            .getLayoutParams();
//                    lp.leftMargin = (int) (-(1 - positionOffset)
//                            * (screenWidth * 1.0 / 2) + currentIndex
//                            * (screenWidth / 2));
//                    mTabLine.setLayoutParams(lp);
//                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        mViewPager.setCurrentItem(0);
    }

    private void initDatas() {
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mFragments.get(arg0);
            }
        };
        mViewPager.setAdapter(mAdapter);
        mViewPager.setCurrentItem(currentIndex);
    }

    private void initFragments() {
        Bundle bundle = new Bundle();
        bundle.putString(MessageModel.TNB, tnb);
        tab01 = new TaskInfoTab01();
        tab01.setArguments(bundle);
//        tab02 = new TaskInfoTab02();
//        tab02.setArguments(bundle);
        mFragments.add(tab01);
        // mFragments.add(tab02);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.add(R.id.fragments, tab01);
        ft.commit();
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        // 接收TRPT信息，刷新页面
        if (MessageModel.TRPT.equals(serviceId)) {
            try {

                SubmittaskprocssResponse resp = (SubmittaskprocssResponse) response;
                SubmitTaskProcessResponseVO vo = resp.getSubmitTaskProcessResponseVO();
                //判断TRPT返回的消息是否与当前页面一致
                if (this.tnb.equals(vo.getTnb())) {
                    if ("S".equals(vo.getStat())) {
                        EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.report) + task.getProcessMap().get(vo.getPcid()).getPCNM() + getString(R.string.succeed) + getString(R.string.TRA_14), false);
                        if (MessageModel.TEND.equals(vo.getPcid())) {
                            finish();
                        } else {
                            Refresh();
                        }
                    } else {
                        EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, vo.getEms(), false);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 接收上报车号信息，刷新页面
        else if (MessageModel.TRBD.equals(serviceId)) {
            try {
                SubmittaskvnbResponse resp = (SubmittaskvnbResponse) response;
                SubmitTaskVnbResponseVO vo = resp.getSubmitTaskVnbResponseVO();
                //判断TRPT返回的消息是否与当前页面一致
                if (this.tnb.equals(vo.getTnb())) {
                    Refresh();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(MessageModel.UCBD.equals(serviceId)){
            Refresh();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TaskInfoTab01.REQUESTCODE_CAMERA) {
            tab01.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void Refresh() {
        if (tab01.isVisible()) {
            tab01.removeButton();
            tab01.updateUI();
        }
//        tab02.refresh();
    }

    @Override
    protected void updateUI(String tag) {
        if(MessageModel.UCUB.equals(tag)){
            Refresh();
        } else if (MessageModel.CDOF.equals(tag)) {
            tab01.receiveCDOF();
        }
    }

    @Override
    protected void updateUI(String tag, String tnb) {
        if (tag.equals(MessageModel.REFRESH)) {
            //如果发生变化的tnb与当前的tnb相同，刷新
            if (tnb.equals(this.tnb)) {
               if(MessageModel.TEND.equals(task.getPID()) || MessageModel.TCXX.equals(task.getPID()) || task.getPID().equals(MessageModel.TRJT)){
                   finish();
               }else {
                   Refresh();
               }
            }
        }
    }

    @Override
    public void onClick(View v) {
//        if (v.equals(mTabtask)) {
//            mViewPager.setCurrentItem(0);
//        } else if (v.equals(mTabtaskdone)) {
//            mViewPager.setCurrentItem(1);
//        }
    }

    /**
     * 重置颜色
     */
    protected void resetTextView() {
//        tabText1.setTextColor(getResources().getColor(R.color.black));
//        tabText2.setTextColor(getResources().getColor(R.color.black));
    }

    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {

        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeight = dm.heightPixels;

        Log.i("", "---------两次时间大于了0.5S--------");
        if(e2.getEventTime() - e1.getEventTime()>500)
        {
            return true;
        }

        if (e1.getX() - e2.getX() > (screenWidth/2)) {
            try {
                tab01.lastTask();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        } else if (e1.getX() - e2.getX() < -(screenWidth/2)) {
            try {
                tab01.nextTask();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		return this.detector.onTouchEvent(event);
	}

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        this.detector.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onMenuKeyDown() {
        tab01.onMenuKeyDown();
    }
}
